%{
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "symbole.h"
#include "tabSymbole.h"

#include "y.tab.h"

extern int numLigne;
//extern union yylval;

extern algo * algo_current;

void yyerror(const char *erreurMsg);
%}

blancs    [ \t]+
CHAINE (([a-z|_]|[0-9a-z_])*)
NOMBRE ([0-9]+)
OPERATEUR ["-"|"+"|"*"|"/"|"%"]

%%

{blancs}  { /* On ignore */ }

"si" {return SI;}
"sinon" {return SINON;}
"faire" {return FAIRE;}
"tantque" {return TANTQUE;}
"finsi" {return FINSI;}
"sinonsi" {return SINONSI;}
"fintantque" {return FINTANTQUE;}
"debut" {return DEBUT;}
"fin" {return FIN;}
"alors" {return ALORS;}
"et" {return ET;}
"ou" {return OU;}

"<" {return INF;}
"<=" {return INFEGAL;}
">" {return SUP;}
">=" {return SUPEGAL;}
"=" {return EGALEGAL;}
"!=" {return NONEGAL;}
"(" {return PAR_OUV;}
")" {return PAR_FER;}
"()" {return PAR;}
"," {return VIR;}

"algorithme" {return ALGORITHME;}

"finfichier" {return FIN_FICHIER;}

\n { ++numLigne; }

{OPERATEUR} {return *yytext;}
{NOMBRE} {yylval.val = atoi(yytext);return ENTIER;}

{CHAINE} {
			symbole * ret = (symbole *)malloc(sizeof(struct symbole));
			//printf("TEST\n");
			char * temp = (char*)malloc(sizeof(char));
			sprintf(temp,"");
			int l = strlen(yytext);
			int i=0;
			for(i=0;i<l;i++){
				char * c = (char*)malloc(sizeof(char));
				sprintf(c,"%c",toupper(*(yytext+i)));
				strcat(temp,c);
				
			}
			if(algo_current==NULL)
				ret = NULL;
			else{
				ret = (symbole *)rechercher(algo_current->ts,temp);
				//ret=NULL;
			}
			if(ret==NULL) {
				//printf("\n----\nTEST STR\n----\n");
				yylval.cha = malloc(sizeof(char *));
				strcpy(yylval.cha,temp);
				return STR;
				
			} else {
				//printf("\n----\nTEST STR TROUVE SYMBOLE\n----\n");
				yylval.symbole = ret;
				switch(ret->type) {
					case SYMBOLE_ACTION :
						return ACTION;
						break;
					case SYMBOLE_VARIABLE :
						return VARIABLE;
						break;
					case SYMBOLE_VARIABLE_USER : 
						return VARIABLE;
						break;
					case SYMBOLE_CONSTANTE :
						return CONSTANTE;
						break;
					case SYMBOLE_FONCTION :
						return FONCTION;
						break;
				}
			}
}

%%

int yywrap(void){
	return 1;
}

void yyerror(const char *erreurMsg) {
  fprintf(stderr, "\n Erreur '%s' à la ligne %d sur '%s'.", erreurMsg, numLigne, yytext);
  exit(-1);
}